package main_test

import (
	"bufio"
	"bytes"
	"fmt"
	"log"
	"os"
	"reflect"
	"regexp"
	"strings"
	"time"

	"github.com/mitchellh/mapstructure"
)

func test1() {

	file, err := os.Open("x.env")

	if err != nil {
		log.Fatalf("failed to open")

	}

	// The bufio.NewScanner() function is called in which the
	// object os.File passed as its parameter and this returns a
	// object bufio.Scanner which is further used on the
	// bufio.Scanner.Split() method.
	scanner := bufio.NewScanner(file)

	// The bufio.ScanLines is used as an
	// input to the method bufio.Scanner.Split()
	// and then the scanning forwards to each
	// new line using the bufio.Scanner.Scan()
	// method.
	scanner.Split(bufio.ScanLines)
	var text []string

	for scanner.Scan() {
		text = append(text, scanner.Text())
	}

	// The method os.File.Close() is called
	// on the os.File object to close the file
	file.Close()

	// and then a loop iterates through
	// and prints each of the slice values.
	for _, each_ln := range text {
		fmt.Println("\"", each_ln, "\",")
	}
}

func removeParentheses(strInfo string) string {
	strReg := "\\(.*?\\)|\\{.*?}|\\[.*?]|（.*?）"
	reg := regexp.MustCompile(strReg)
	return reg.ReplaceAllString(strInfo, "")
}

func test2() {
	str := "好喝（的蜜）桃(乌龙茶，)哈(哈)哈"
	//compileRegex, _ := regexp.Compile(`[^桃]`)
	strReg := "\\(.*?\\)|\\{.*?}|\\[.*?]|（.*?）"
	compileRegex := regexp.MustCompile(strReg) // 正则表达式的分组，以括号()表示，每一对括号就是我们匹配到的一个文本，可以把他们提取出来。
	//compileRegex := regexp.MustCompile("好喝的(.*?)，哈哈哈") // 正则表达式的分组，以括号()表示，每一对括号就是我们匹配到的一个文本，可以把他们提取出来。
	//matchArr := compileRegex.FindStringSubmatch(str) // FindStringSubmatch 方法是提取出匹配的字符串，然后通过[]string返回。我们可以看到，第1个匹配到的是这个字符串本身，从第2个开始，才是我们想要的字符串。
	matchArr := compileRegex.FindAllStringSubmatch(str, -1)
	if len(matchArr) > 0 {
		for k, v := range matchArr {
			fmt.Println(k, v[0])
		}
		//fmt.Println("提取字符串内容：", matchArr[len(matchArr)-1]) // 输出：蜜桃乌龙茶
	}
}

func test3() {
	type Person struct {
		Name  string
		Age   int
		Email string
	}
	data := []map[string]interface{}{
		{
			"Name":  "John Doe",
			"Age":   30,
			"Email": "john.doe@example.com",
		},
		{
			"Name":  "John Doe",
			"Age":   30,
			"Email": "john.doe@example.com",
		},
		{
			"Name":  "John Doe",
			"Age":   30,
			"Email": "john.doe@example.com",
		},
		{
			"Name":  "John Doe",
			"Age":   30,
			"Email": "john.doe@example.com",
		},
	}

	var person []Person
	err := mapstructure.Decode(data, &person)
	if err != nil {
		fmt.Println("Error:", err)
	}
	fmt.Printf("%+v\n", person)
}

func GetFirstDateOfWeek() string {
	now := time.Now()
	offset := int(time.Monday - now.Weekday())
	if offset > 0 {
		offset = -6
	}
	weekStartDate := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.Local).AddDate(0, 0, offset)
	weekMonday := weekStartDate.Format("2006-01-02")
	//fmt.Println("weekMonday", weekMonday)
	return weekMonday
}

func GetLastWeekFirstDate() string {
	thisWeekMonday := GetFirstDateOfWeek()
	TimeMonday, _ := time.Parse("2006-01-02", thisWeekMonday)
	lastWeekMonday := TimeMonday.AddDate(0, 0, -7)
	weekMonday := lastWeekMonday.Format("2006-01-02")
	//fmt.Println("GetLastWeekFirstDate", weekMonday)
	return weekMonday
}

func mayPanic() {
	panic("An error occurred!")
}

func handlePanic() {
	defer func() {
		if r := recover(); r != nil {
			fmt.Println("Recovered from panic:", r)
		}
	}()
	mayPanic()
}

type TimeFormatParams struct {
	Chuo int64
	Tf   string `default:"2006-01-02 15:04:05"`
}

func TimeFormat(tf TimeFormatParams) string {
	if tf.Tf == "" {
		tfp := reflect.TypeOf(tf)
		f, _ := tfp.FieldByName("Tf")
		tf.Tf = f.Tag.Get("default")
	}
	fmt.Println(tf)
	tm := time.Unix(tf.Chuo, 0)
	timeStr := tm.Format(tf.Tf)
	fmt.Println(timeStr)
	return timeStr
}

func test_string() {
	var buffer bytes.Buffer
	buffer.WriteString("hello")
	buffer.WriteString(",")
	buffer.WriteString("world")
	fmt.Println("buffer", buffer.String())
	var sb strings.Builder
	sb.WriteString("hello")
	sb.WriteString(" ")
	sb.WriteString("world")
	fmt.Println("sb", sb.String())
}

func test_channel() {
	ch := make(chan int, 1) // 创建一个类型为int，缓冲区大小为1的channel
	ch <- 2                 // 将2发送到ch
	n, ok := <-ch           // n接收从ch发出的值
	if ok {
		fmt.Println(n) // 2
	}
	close(ch) // 关闭channel
}

func test_channel2() {
	ci := make(chan int, 2)
	for i := 0; i < 2; i++ {
		ci <- i
	}
	close(ci)

	cs := make(chan string, 2)
	cs <- "hi"
	cs <- "golang"
	close(cs)

	ciClosed, csClosed := false, false

	for {
		if ciClosed && csClosed {
			return
		}
		select {
		case i, ok := <-ci:
			if ok {
				fmt.Println(i)
			} else {
				ciClosed = true
				fmt.Println("ci closed")
			}
		case s, ok := <-cs:
			if ok {
				fmt.Println(s)
			} else {
				csClosed = true
				fmt.Println("cs closed")
			}
		default:
			fmt.Println("waiting...")
		}
	}
}

// func test_multiProcess() {
// 	fmt.Println("当前进程ID：", os.Getpid())

// 	procAttr := &os.ProcAttr{
// 		Files: []*os.File{os.Stdin, os.Stdout, os.Stderr},
// 	}
// 	process, err := os.StartProcess("/bin/echo", []string{"", "hello,world!"}, procAttr)
// 	if err != nil {
// 		fmt.Println("进程启动失败:", err)
// 		os.Exit(2)
// 	} else {
// 		fmt.Println("子进程ID：", process.Pid)
// 	}

// 	time.Sleep(time.Second)
// }

func test4() {
	// fmt.Println("1 << 63", uint64(1<<63))
	fmt.Println("1 >> 63", 1>>63)
	fmt.Println("1 << 63", 1<<2)
	fmt.Println("1 >> 63", int64(1>>63))
}

func Main1() {
	//test2()
	//test2()
	//fmt.Println(removeParentheses("好喝的蜜桃(乌龙茶，)哈(哈)哈"))
	//test3()
	//GetFirstDateOfWeek()
	//w := GetLastWeekFirstDate()
	//s, _ := time.Parse("2006-01-02", w)
	//e := s.AddDate(0, 0, 7)
	//fmt.Println("s, e", s.Unix()-8*3600, e.Unix()-8*3600)
	//handlePanic()
	//TimeFormat(TimeFormatParams{Chuo: 1735024232})
	//logger.LogInit()
	//logger.Logger.Error("这个是一个错误日志")
	// test_string()
	// test_channel()
	//ollama run qwen2.5-coder:7b
	// test_channel2()
	test4()
}
